import time

keywords_list=["heartrate","cadence","power","distance"]

def read_gpx(gpx):
    first_time=0
    first_str_time=""
    trkpt_flag=0
    j=0
    
    num_list=[0]
    time_list=[None]
    ele_list=[None]
    lat_list=[None]
    lon_list=[None]
    key_list=[]
    
    gpx_dict={}
    key_dict={}
    
    for i in keywords_list:
        key_list.append([None])
        
    for i in range(len(gpx)):        
        try:
            ti=str((gpx[i].split("<time>")[1]).split("</time>")[0])
            now_time = time.mktime(time.strptime(ti, "%Y-%m-%dT%H:%M:%SZ"))
            first_time=now_time                
            first_str_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(first_time))  
            break
        except:
            pass
    time_list[0]=first_str_time
    
    for i in range(len(gpx)):
        if gpx[i].count('<trkpt'):
            trkpt_flag=1      
            j=j+1
            num_list.append(j)
            time_list.append(j)
            ele_list.append(j)
            lat_list.append(j)
            lon_list.append(j)            
            for k in range(len(keywords_list)):
                key_list[k].append(j)

        if trkpt_flag==1:
            try:
                ti=str((gpx[i].split("<time>")[1]).split("</time>")[0])
                now_time = time.mktime(time.strptime(ti, "%Y-%m-%dT%H:%M:%SZ"))
                now_str_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(now_time))  
                time_list[j]=now_str_time
            except:
                pass
            
            if gpx[i].count('<trkpt'):
                lat_list[j]=float(gpx[i].split('"')[1])
                lon_list[j]=float(gpx[i].split('"')[3])
                
            try:
                ele_list[j]=float(str((gpx[i].split("<ele>")[1]).split("</ele>")[0]))
            except:
                pass
            
            for k in range(len(keywords_list)):           
                try:
                    dat=str((gpx[i].split("<"+keywords_list[k]+">")[1]).split("</"+keywords_list[k]+">")[0])
                    key_list[k][j]=float(dat)
                except:
                    pass

        if gpx[i].count('</trkpt>'):
            trkpt_flag=0
        
        if gpx[i].count('</trkseg>'):
            break
        
    gpx_dict["num"]=num_list    
    gpx_dict["time"]=time_list       
    gpx_dict["lat"]=lat_list
    gpx_dict["lon"]=lon_list
    gpx_dict["ele"]=ele_list 
    for k in range(len(keywords_list)):
        key_dict[keywords_list[k]]=key_list[k]
    
    gpx_dict["key"]=key_dict
    return gpx_dict

